package top.fzqblog.kotlinapp.fragment

import android.annotation.TargetApi
import android.app.ActivityOptions
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.view.ViewCompat
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.jcodecraeer.xrecyclerview.XRecyclerView
import kotlinx.android.synthetic.main.fragment_sell.*
import org.jetbrains.anko.support.v4.startActivity
import top.fzqblog.filterview.entity.FilterUrl
import top.fzqblog.filterview.interfaces.OnFilterDoneListener
import top.fzqblog.kotlinapp.R
import top.fzqblog.kotlinapp.activity.HouseDetailActivity
import top.fzqblog.kotlinapp.adapter.FilterMenuAdapter
import top.fzqblog.kotlinapp.adapter.HouseAdapter
import top.fzqblog.kotlinapp.func.applySchedulers
import top.fzqblog.kotlinapp.func.log
import top.fzqblog.kotlinapp.http.ApiRetrofit
import top.fzqblog.kotlinapp.http.DistrictService
import top.fzqblog.kotlinapp.http.HouseService
import top.fzqblog.kotlinapp.http.ZoneService
import top.fzqblog.kotlinapp.listener.OnItemClickListener
import top.fzqblog.kotlinapp.model.District
import top.fzqblog.kotlinapp.model.House
import top.fzqblog.kotlinapp.model.HouseResult
import top.fzqblog.kotlinapp.model.Zone
import java.util.ArrayList

/**
* Created by 抽离 on 2017/11/13 0013.
*/
class Sell: Fragment(), OnFilterDoneListener {

    private var houseAdapter: HouseAdapter? = null

    private val size = 10

    private var page = 1

    private var total = 1000

    private var list: ArrayList<String>? = null

    override fun onFilterDone(position: Int, positionTitle: String?, urlValue: String?) {
        if (position != 3) {
            filterView?.setPositionIndicatorText(FilterUrl.instance().position, FilterUrl.instance().positionTitle)
        }
        log("position:" + FilterUrl.instance().position + "=====positionTitle:" + FilterUrl.instance().positionTitle)
        filterView?.close()
    }


    private fun initFilterDropDownView() {
        val titleList = arrayOf("区域", "户型", "价格", "更多")
        log("filterView--------------------------：" + filterView)
        log("activity-----------------------------：" + activity)
        filterView?.setMenuAdapter(FilterMenuAdapter(activity, titleList, this))
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        log("sell------onCreateView")
        val view = inflater?.inflate(R.layout.fragment_sell, container, false)
        log("view--------------:"+view.toString())
        return view
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        log("sell------onActivityCreated")
        initFilterDropDownView()
//        initBaseData()
        initContentView()

//                val apiRetrofit: ApiRetrofit =  ApiRetrofit.getInstance(activity)
//                val loginService = apiRetrofit.create(LoginService::class.java)
//                loginService!!
//                        .getLoginResult()
//                        .subscribe{
//                            loginResult: LoginResult? ->
//                            log(loginResult.toString())
//                        }
//
//
//                val houseService = apiRetrofit.create(HouseService::class.java)
//                houseService!!
//                        .getHouseByCondition()
//                        .subscribe {
//                            houseResult: HouseResult? ->
//                            log(houseResult.toString())
//
//                        }
//
//                val custService = apiRetrofit.create(CustService::class.java)
//                custService!!
//                        .getCustByCondition()
//                        .subscribe({
//                            custResult ->
//                            log(custResult.toString())
//                        },{
//                            throwable ->
//                            log("未登录")
//                        })


        }

    private fun initBaseData() {
        val apiRetrofit: ApiRetrofit =  ApiRetrofit.getInstance(activity)
        val zoneService = apiRetrofit.create(ZoneService::class.java)
        zoneService!!
                .getZoneListByDistrict("思明")
                .applySchedulers()
                .subscribe {
                    zones ->
                    log(zones.toString())
                }
    }

    private fun initContentView() {
        val apiRetrofit: ApiRetrofit =  ApiRetrofit.getInstance(activity)
        val houseService = apiRetrofit.create(HouseService::class.java)

        mFilterContentView.layoutManager = LinearLayoutManager(activity)
        mFilterContentView.setLoadingListener(object : XRecyclerView.LoadingListener{
            override fun onLoadMore() {
                log("loadMore-----------page-------$page-------total--------$total")
                if(page * 10 >= total){
                    mFilterContentView.setNoMore(true)
                    return
                }
                page ++
                val house: House = House(page.toString() , size.toString())
                val houseStr: String = Gson().toJson(house)
                val gson: Gson = GsonBuilder().create()
                val map = gson.fromJson(houseStr, Map::class.java)
                houseService!!
                        .getHouseByCondition(map as Map<String, String>)
                        .applySchedulers()
                        .subscribe {
                            houseResult: HouseResult ->
                            houseAdapter?.addAll(houseResult.page.records)
                            mFilterContentView.loadMoreComplete()
                            houseAdapter?.notifyDataSetChanged()
                            setItemClickListener()
                        }
            }

            override fun onRefresh() {
                page = 1
                list = ArrayList()

                val house: House = House(page.toString(), size.toString())
                val houseStr: String = Gson().toJson(house)
                val gson: Gson = GsonBuilder().create()
                val map = gson.fromJson(houseStr, Map::class.java)
                log("map:-----------------------" + map)
                houseService!!
                        .getHouseByCondition(map as Map<String, String>)
                        .applySchedulers()
                        .subscribe {
                            houseResult: HouseResult ->
                            total = houseResult.page.total
                            houseAdapter = HouseAdapter(activity, houseResult.page.records)
                            mFilterContentView.adapter = houseAdapter
                            mFilterContentView.refreshComplete()
                            houseAdapter?.notifyDataSetChanged()
                            setItemClickListener()
                        }
            }

        })

//        mFilterContentView.addItemDecoration(RecycleViewDivider(activity, LinearLayoutManager.HORIZONTAL))

        mFilterContentView.refresh()


    }

    fun setItemClickListener(){
        houseAdapter?.setClickListener(object: OnItemClickListener{
            override fun onClick(position: Int, houseId: Long, url:String, imageView: ImageView) {
                toDetail(houseId, url, imageView)
//                startActivity<HouseDetailActivity>("houseId" to houseId)
            }
        })
    }

    @TargetApi(19)
    fun toDetail(houseId: Long, url: String, imageView: ImageView){
        val intent = Intent(activity, HouseDetailActivity::class.java)
        intent.putExtra("houseId", houseId)
        intent.putExtra("url", url)
        intent.putExtra("transitionName", ViewCompat.getTransitionName(imageView))
        if(Build.VERSION.SDK_INT >= 21){
            log("sdk>>>>>>>>>======21")
            startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(activity, imageView, ViewCompat.getTransitionName(imageView)).toBundle())//context, 转场的元素，转场transitionName

        }else{
            log("sdk<<<<<<<<<<<<<<<21")
            startActivity(intent)
        }
    }

    override fun onDestroy() {
            super.onDestroy()
            FilterUrl.instance().clear()
        }
    }

